# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--si", default = "1;0", type = "character", help = "step"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()

accordKind  <- configJson$datas$accordKind[step]
calculateMethod  <- configJson$datas$calculateMethod[step]
keepMethod  <- configJson$datas$keepMethod[step]
constant  <- configJson$datas$constant[step] %>%
  as.numeric()
topN  <- configJson$datas$topN[step] %>%
  as.numeric()
topPercent  <- configJson$datas$topPercent[step] %>%
  as.numeric()

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1)

selectData <- if (accordKind == "qc") {
  data %>%
    select_at(vars(starts_with("QC"), "Metabolite"))
}else if (accordKind == "noQc") {
  data %>%
    select_at(vars(!starts_with("QC")))
}else {
  data
}

indData <- selectData %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    data <- result %>%
      select(-c("Metabolite")) %>%
      unlist()
    result$ind <- if (calculateMethod == "median") {
      median(data)
    }else {
      mean(data)
    }
    result
  }) %>%
  ungroup()

rowNames <- if (keepMethod == "more") {
  indData %>%
    filter(ind > constant) %>%
    .$Metabolite
}else if (keepMethod == "top") {
  indData %>%
    arrange(desc(ind)) %>%
    slice(1:topN) %>%
    .$Metabolite
}else {
  curTopN <- max(1, (nrow(data) * topPercent) / 100)
  indData %>%
    arrange(desc(ind)) %>%
    slice(1:curTopN) %>%
    .$Metabolite
}

outData <- data %>%
  filter(Metabolite %in% rowNames)

outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".level_filter_var.csv"))








